package org.jfinanceobserver.tmp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.jfinanceobserver.persistence.jpa.controller.QuotePropertyJpaController;
import org.jfinanceobserver.persistence.jpa.entities.QuoteProperty;
import org.jfinanceobserver.utillities.CVSParser;
import org.jfinanceobserver.utillities.Util;

/**
 * This is a temporal class to perform some quick test
 *
 * $Author: r78v10a07@gmail.com $ $LastChangedDate: 2013-02-12 09:59:23 +0000 (Tue, 12 Feb 2013) $ $LastChangedRevision: 19 $
 *
 * @since Feb 10, 2013
 */
public class App {

    private StringBuilder values;
    private Connection conn = null;
    private List<QuoteProperty> quotes;
    private EntityManagerFactory factory = null;
    private QuotePropertyJpaController qController = null;
    public final String[] QUOTES = {"GOOG", "ORCL", "AMZN", "AAPL", "FB", "MSFT", "AMD", "YHOO", "NVDA", "INTC", "DELL"};
    public final String QUOTES2 = "GOOG,ORCL,AMZN,AAPL,FB,MSFT,AMD,YHOO,NVDA,INTC,DELL";

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public EntityManagerFactory getFactory() {
        return factory;
    }

    public void setFactory(EntityManagerFactory factory) {
        this.factory = factory;
    }

    public void mysql() {
        try {
            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/finance";
            String user = "finance";
            String passwd = "mypass";

            try {
                Class.forName(driver).newInstance();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            }

            java.util.Properties conProperties = new java.util.Properties();
            conProperties.put("user", user);
            conProperties.put("password", passwd);
            conProperties.put("autoReconnect", "true");
            conProperties.put("maxReconnects", "2");
            conn = DriverManager.getConnection(url, conProperties);
        } catch (SQLException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public int executeUpdate(String sql) throws SQLException {
        int count;
        try (Statement s = conn.createStatement()) {
            count = s.executeUpdate(sql);
        }
        return count;
    }

    public void quotes() {
        HashMap parm = new HashMap<>();
        parm.put("active", true);
        values = new StringBuilder();
        qController = new QuotePropertyJpaController(factory);
        quotes = qController.useNamedQuery("QuoteProperty.findByActive", parm);

        if (!quotes.isEmpty()) {
            Iterator it = quotes.iterator();
            while (it.hasNext()) {
                QuoteProperty q = (QuoteProperty) it.next();
                values.append(q.getTag());
            }
        }
    }

    public void urlSearch() throws IOException {
        try {
            String url = "http://download.finance.yahoo.com/d/quotes.csv?s=" + QUOTES2 + "&f=" + values.toString() + "&ignore=.csv";
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    if (!inputLine.isEmpty()) {
                        StringBuilder column = new StringBuilder();
                        column.append("INSERT INTO test (");
                        if (!quotes.isEmpty()) {
                            Iterator it = quotes.iterator();
                            while (it.hasNext()) {
                                QuoteProperty q = (QuoteProperty) it.next();
                                column.append(q.getName()).append(",");
                            }
                        }
                        column.append("LoadTime) VALUES (");
                        String[] val = CVSParser.parse(inputLine);
                        for (int i = 0; i < val.length; i++) {
                            column.append("'").append(val[i].replace("\"", "")).append("'").append(",");
                        }
                        column.append(" NOW())");
                        try {
                            executeUpdate(column.toString());
                        } catch (SQLException ex) {
                            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String createTestTable() throws IOException {
        StringBuilder seq = new StringBuilder();
        quotes();
        if (!quotes.isEmpty()) {
            seq.append("CREATE TABLE IF NOT EXISTS test (\n");
            Iterator it = quotes.iterator();
            while (it.hasNext()) {
                QuoteProperty q = (QuoteProperty) it.next();
                seq.append("`").append(q.getName()).append("` VARCHAR(50),\n");
            }
            seq.append("`LoadTime` DATETIME)");
        }
        return seq.toString();
    }

    public void runTest() throws IOException, SQLException, ParseException {
        int i = 0;
        while (true) {
            Date now = new Date();
            if (now.after(Util.getInstance().openDate()) && now.before(Util.getInstance().closeDate())) {
                i++;
                if (getFactory() == null || !getFactory().isOpen()) {
                    setFactory(Persistence.createEntityManagerFactory("com.rvera_jfinance"));
                }
                if (getConn() == null || getConn().isClosed()) {
                    mysql();
                    executeUpdate(createTestTable());
                }
                System.out.println("Iter: " + i + " " + (new Date()).toString());
                urlSearch();
                try {
                    Thread.sleep(Util.getInstance().openInterval);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            } else {
                if (getFactory() != null && getFactory().isOpen()) {
                    getFactory().close();
                    setFactory(null);
                }
                if (getConn() != null && !getConn().isClosed()) {
                    getConn().close();
                    setConn(null);
                }
                System.out.println("Market close until: " + Util.getInstance().openDate() + " current time: " + (new Date()).toString());
                try {
                    Thread.sleep(Util.getInstance().closeInterval);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException, SQLException, ParseException {
        int i = 0;
        App instance = new App();
        instance.runTest();
    }
}
